package com.tuoyu.peopletest.view.ac;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.KeyboardUtils;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.stresscube.usbdevice.USBDevicePDHIDWithAddress;
import com.tuoyu.peopletest.R;
import com.tuoyu.peopletest.entity.DataBean;
import com.tuoyu.peopletest.utils.SCTimeUtils;
import com.tuoyu.peopletest.utils.SettingsClass;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Set;

public class MainActivityRED extends AppCompatActivity implements View.OnClickListener {
    static final String TAG = "Main";
    static final byte testColor = 0x15; //测试使用的颜色， 15为波长365，2A为波长470

    Button mBtn365, mBtn470, mBtn525_1, mBtn525_2;
    EditText mEdtADGain;
    EditText mEdtStart;
    EditText mEdtStop;
    EditText mEdtStep;
    SeekBar mSBBrightness;
    CheckBox mcbColor1, mcbColor2, mcbColor3, mcbColor4, mcbColor5, mcbColor6;
    RadioGroup mrgP1LED, mrgADPosition;
    //    USBDeviceHID mDeviceHID = new USBDeviceHID();
    USBDevicePDHIDWithAddress mDeviceHID = new USBDevicePDHIDWithAddress();
    LineChart mLineChart;   //显示曲线
    TextView mtvResult; //结果显示
    //    byte position = 2, color = 1; //孔位为2，颜色为1
//    byte ledPosition = (byte)0xF1, color = 0x0c; //孔位为2，颜色为1
    byte ledPosition = (byte) 0x03, color = (byte) 0x15; //孔位为3，颜色为全亮
    byte adPosition = (byte) 0x01;
    boolean mbLED470Clicked = false;
    //    byte adPosition = 2; //孔位为2，颜色为1
    //    ArrayList<ArrayList<Integer>> mListResult = new ArrayList<ArrayList<Integer>>(); //保存读出来的波长数据，一次10个波长
    ArrayList<Integer> mListResult = new ArrayList<>(); //保存读出来的数据
    boolean[] bF8ClearNIR = new boolean[]{true, true, true, true, true, true, true, true, true, true}; //是否选择各个波长
//    String[] mstrWaveLength = {"F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "clear", "NIR"};

    int mStart, mStop, mStep; //起始位置、终止位置、每步几个点（最少1个点，此时采样频率为50Hz，为2时，采样频率为100Hz）
    private EditText etNumber;
    private String mArea1;
    private String mArea2;
    private String waveLength;
    private EditText etProject;

    //    final int MAX_PEAK = 550 * 1000;
    final int MAX_PEAK = 260 * 10000;
    byte gain = 0x0f, amplify = 43;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main_red);

        InitData();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mDeviceHID.init(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mDeviceHID.release();
    }

    void InitData() {
        //findViewById(R.id.v_et_main).setVisibility(View.VISIBLE);
        etNumber = findViewById(R.id.et_input);
        mBtn365 = findViewById(R.id.btn365);
        mBtn470 = findViewById(R.id.btn470);
        mBtn525_1 = findViewById(R.id.btn525_1);
        mBtn525_2 = findViewById(R.id.btn525_2);
        ResetBtnClicked();

        mEdtADGain = findViewById(R.id.edtADGain);
        mEdtStart = findViewById(R.id.edtStart);
        mEdtStop = findViewById(R.id.edtStop);
        mEdtStep = findViewById(R.id.edtStep);

        mtvResult = findViewById(R.id.tvResult);
        mLineChart = findViewById(R.id.lineChart_01);
        mSBBrightness = findViewById(R.id.sbBrightness);
        mSBBrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                ((TextView) findViewById(R.id.tvBrightness)).setText(String.valueOf(progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        mListResult.clear();
        mcbColor1 = findViewById(R.id.cbLight1);
        mcbColor2 = findViewById(R.id.cbLight2);
        mcbColor3 = findViewById(R.id.cbLight3);
        mcbColor4 = findViewById(R.id.cbLight4);
        mcbColor5 = findViewById(R.id.cbLight5);
        mcbColor6 = findViewById(R.id.cbLight6);

        mrgP1LED = findViewById(R.id.rgP1LED);
        mrgP1LED.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                openP1LED(checkedId);
            }
        });

        mrgADPosition = findViewById(R.id.rgADPosition);

        SettingsClass.getSettings();
        mSBBrightness.setProgress(SettingsClass.getMainRedBrightness());
        mEdtStart.setText(SettingsClass.getMainRedStart()+"");
        mEdtStop.setText(SettingsClass.getMainRedStop()+"");
    }

    //打开孔1的LED灯，或者孔1关灯
    private void openP1LED(int checkedId) {
        if (checkedId == R.id.rbP1LEDOff) {
            p1LEDOff();
            return;
        }
        byte color = 0x00;
        if (checkedId == R.id.rbP1LED1)
            color = 0x01;
        else if (checkedId == R.id.rbP1LED2)
            color = 0x02;
        else if (checkedId == R.id.rbP1LED3)
            color = 0x04;
        else if (checkedId == R.id.rbP1LED4)
            color = 0x08;
        else if (checkedId == R.id.rbP1LED5)
            color = 0x10;
        else if (checkedId == R.id.rbP1LED6)
            color = 0x20;
        else if (checkedId == R.id.rbP1LED7)
            color = 0x40;
        else if (checkedId == R.id.rbP1LED8)
            color = (byte) 0x80;
        else if (checkedId == R.id.rbP1LEDLaser)
            color = (byte) 0xa1;

        ledPosition = 0x01;
        int brightness = mSBBrightness.getProgress();
        if (!mDeviceHID.LEDOn(ledPosition, color, brightness))
            DisplayMessage("孔1开灯失败");
        else
            DisplayMessage("孔1开灯成功");
    }

    private void p1LEDOff() {
        boolean bSuccess;
        bSuccess = mDeviceHID.LEDOn((byte) 0x01, (byte) 0x00, 0);
        if (!mDeviceHID.LEDOn((byte) 0x01, (byte) 0xa0, 0) || !bSuccess)
            DisplayMessage("孔1关灯失败");
        else
            DisplayMessage("孔1关灯成功");
        ledPosition = 0x03;
    }

    public void DisplayMessage(String msg) {
        Log.d(TAG, msg);
        msg += "\r\n" + mtvResult.getText();
        mtvResult.setText(msg);
    }

    public void DisplayAreaMessage(String msg) {
        ((TextView) findViewById(R.id.tvResultArea)).setText(msg);
        Log.d(TAG, msg);
    }

    public void DisplayAverageMessage(String msg) {
        ((TextView) findViewById(R.id.tvResultAverage)).setText(msg);
        Log.d(TAG, msg);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvStop:
                clickTextViewStop();
                break;
            case R.id.btnAdd: {
                int progress = mSBBrightness.getProgress();
                progress++;
                if (progress > 800) progress = 800;
                mSBBrightness.setProgress(progress);
                break;
            }
            case R.id.btnSub: {
                int progress = mSBBrightness.getProgress();
                progress--;
                if (progress < 0) progress = 0;
                mSBBrightness.setProgress(progress);
                break;
            }
            case R.id.btnLEDOn:
                LEDOn();
                break;
            case R.id.btnLEDOff:
                LEDOff();
                break;
            case R.id.btnHome:
                Home();
                break;
            case R.id.btnTrayOut:
                TrayOut();
                break;
            case R.id.btnTrayIn:
                TrayIn();
                break;
            case R.id.btnTrayMoveStart:
                TrayMoveStart();
                break;
            case R.id.btnTrayMoveEnd:
                TrayMoveEnd();
                break;
            case R.id.btnScanRead:
                ScanRead();
                break;
            case R.id.btnMainTest:
                Intent mainTestIntent = new Intent(this, MainActivityTest.class);
                startActivity(mainTestIntent);
                finish();
                break;
            case R.id.btnRead:
                Read();
                break;
            case R.id.cbF1:
                ClickF8ClearNIR(1);
                break;
            case R.id.cbF2:
                ClickF8ClearNIR(2);
                break;
            case R.id.cbF3:
                ClickF8ClearNIR(3);
                break;
            case R.id.cbF4:
                ClickF8ClearNIR(4);
                break;
            case R.id.cbF5:
                ClickF8ClearNIR(5);
                break;
            case R.id.cbF6:
                ClickF8ClearNIR(6);
                break;
            case R.id.cbF7:
                ClickF8ClearNIR(7);
                break;
            case R.id.cbF8:
                ClickF8ClearNIR(8);
                break;
            case R.id.cbClear:
                ClickF8ClearNIR(9);
                break;
            case R.id.cbNIR:
                ClickF8ClearNIR(10);
                break;
            case R.id.cbLight1:
            case R.id.cbLight2:
            case R.id.cbLight3:
            case R.id.cbLight4:
            case R.id.cbLight5:
            case R.id.cbLight6:
                SetColor();
                break;
            case R.id.btn365:
                OpenLED365();
                waveLength = mBtn365.getText().toString().trim();
                break;
            case R.id.btn470:
                OpenLED470();
                waveLength = mBtn470.getText().toString().trim();
                break;
            case R.id.btn525_1:
                OpenLED525_1();
                waveLength = mBtn525_1.getText().toString().trim();
                break;
            case R.id.btn525_2:
                OpenLED525_2();
                waveLength = mBtn525_2.getText().toString().trim();
                break;
            /*   case R.id.tv_btn_sure:
             //样本输入确定
                etProject = findViewById(R.id.et_input_project);
                if (etNumber.getText().toString().equals("")
                        || etProject.getText().toString().equals("")
                ) {
                    Toast.makeText(this, "请完善信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                KeyboardUtils.hideSoftInput(this);
                findViewById(R.id.v_et_main).setVisibility(View.GONE);
                break;*/
            case R.id.cbColor470_1:
            case R.id.cbColor470_2:
            case R.id.cbColor470_3:
                SetColor470();
                break;
            case R.id.btnMain:
                startActivity(new Intent(this, MainActivity.class));
                break;
        }
    }

    static long timeStart=0;
    static int iClickTimes=0;
    private void clickTextViewStop() {
        long now = System.currentTimeMillis();
        if(timeStart==0) {
            timeStart=now;
            iClickTimes=1;
            return;
        }
        if(now-timeStart>2000) {
            timeStart=now;
            iClickTimes=1;
            return;
        }
        timeStart=now;
        iClickTimes++;
        if(iClickTimes>5) {
            iClickTimes=0;
            timeStart=0;
            findViewById(R.id.btnMain).setVisibility(View.VISIBLE);
        }
    }

    void showTestDialog(int i) {
        final int ivalue = i;
        if (i < 3) {
            AlertDialog.Builder b = new AlertDialog.Builder(this);//this为上下文，如果在本类里显示，通常使用this
            b.setTitle("测试结果");//对话框标题
            b.setMessage("i=" + i);//提示文本
            b.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int nexti = ivalue + 1;
                    showTestDialog(nexti);
                }
            }); //确定按钮，点击事件和取消按钮一样
            AlertDialog alertDialog = b.create();
            alertDialog.show();   //设置完毕，显示对话框
            alertDialog.getWindow().setLayout(800, 400);
        }
    }

    private void ConvertInt2Bytes(int data, byte[] bytes, int iBuffer) {
        bytes[iBuffer] = (byte) ((data & 0xFF000000) >> 24);
        bytes[iBuffer + 1] = (byte) ((data & 0xFF0000) >> 16);
        bytes[iBuffer + 2] = (byte) ((data & 0xFF00) >> 8);
        bytes[iBuffer + 3] = (byte) (data & 0xFF);
    }

    private int GetIntFromBytes(byte[] bytes, int iBuffer) {
        if (bytes == null || bytes.length <= iBuffer + 4)
            return -1;
        return (((bytes[iBuffer] & 0xFF) * 256 + (bytes[iBuffer + 1] & 0xff)) * 256 + (bytes[iBuffer + 2] & 0xff)) * 256 + (bytes[iBuffer + 3] & 0xff);
    }

    void SetColor470() {
        if (mbLED470Clicked) {
            color = 0x00;
            if (((CheckBox) findViewById(R.id.cbColor470_1)).isChecked())
                color |= 0x20;
            if (((CheckBox) findViewById(R.id.cbColor470_2)).isChecked())
                color |= 0x08;
            if (((CheckBox) findViewById(R.id.cbColor470_3)).isChecked())
                color |= 0x02;
        }
    }

    //计算峰值下的面积，一共2个峰，峰值左右各1mm，确定是向上的峰或向下的谷
    //左向外10个点及右向外10个点，取平均值，确定为基线
    int left = 10, right = 10, minGap = 50;//面积计算时，极值点左右的距离, minGap为两个峰值间的距离， 单位为0.1mm

    boolean getPeakPos(int[] data, List<Integer> listPeakPos, boolean bValley, int step) {
        int max1 = 0, max2 = 0, max2Left = 0, max2Right = 0;
        int iMax1 = 0, iMax2 = 0;
        if (bValley) {
            for (int iData = 0; iData < data.length; iData++) {
                data[iData] *= -1;
            }
            max2Left = max2Right = max1 = -256 * 256 * 256 * 127;
        }
        //找第1个峰
        for (int iData = 0; iData < data.length; iData++)
            if (data[iData] > max1) {
                max1 = data[iData];
                iMax1 = iData;
            }
        //找第2个峰
        int iMax2Left = 0, iMax2Right = 0;
        if (iMax1 > ((left + right) + left) * step) {
            for (int iData = left * step; iData < iMax1 - (left + right) * step; iData++)
                if (data[iData] > max2Left) {
                    max2Left = data[iData];
                    iMax2Left = iData;
                }
        }
        if ((data.length - iMax1) > ((left + right) + right) * step) {
            for (int iData = iMax1 + (left + right) * step; iData < data.length - right * step; iData++)
                if (data[iData] > max2Right) {
                    max2Right = data[iData];
                    iMax2Right = iData;
                }
        }
        if (max2Right > max2Left) {
            max2 = max2Right;
            iMax2 = iMax2Right;
        } else {
            max2 = max1;
            max1 = max2Left;
            iMax2 = iMax1;
            iMax1 = iMax2Left;
        }
        listPeakPos.clear();
        listPeakPos.add(iMax1);
        listPeakPos.add(iMax2);
        return true;
    }

    private String GetArea(int[] data, int step) {
        boolean bValley = ((RadioGroup) findViewById(R.id.rgPeakOrValley)).getCheckedRadioButtonId() != R.id.rbPeakOrValley_Peak;
        List<Integer> listPeakPos = new ArrayList<>();
        getPeakPos(data, listPeakPos, bValley, step);
        if (listPeakPos.size() != 2)
            return "";
        int average = GetAverage(data, listPeakPos.get(0), listPeakPos.get(1), step);

        int[] areaLeft = new int[2];
        int[] areaRight = new int[2];
        int area1 = CalcArea(data, listPeakPos.get(0), step, average, areaLeft);
        int area2 = CalcArea(data, listPeakPos.get(1), step, average, areaRight);
        mArea1 = area1 + "";
        mArea2 = area2 + "";

        int max1 = data[listPeakPos.get(0)], max2 = data[listPeakPos.get(1)];
        double s1s2Ratio1 = ((int) ((areaLeft[0] * 1.0 / areaRight[0]) * 100 + 0.5)) / 100.;
        double s1s2Ratio2 = ((int) ((areaLeft[1] * 1.0 / areaRight[1]) * 100 + 0.5)) / 100.;
        double maxRatio1 = ((int) ((max1 * 1.0 / max2) * 100 + 0.5)) / 100.;
        double maxRatio2 = ((int) (((max1 - average) * 1.0 / (max2 - average)) * 100 + 0.5)) / 100.;
//        SendDispMessage("max1:" + max1 + " max2:" + max2 + "max1:max2="+maxRatio1+" mean:" + average);
//        SendDispMessage("减平均max1:" + (max1-average) + " max2:" + (max2-average) + "max1:max2="+maxRatio2);
//        SendDispMessage("减左侧s1:"+areaLeft[0] + " s2:" + areaRight[0] + " s1:s2="+s1s2Ratio1);
//        SendDispMessage("减平均s1:" + areaLeft[1] + " s2:" + areaRight[1] + " s1:s2="+s1s2Ratio2);
        SendDisplayMessage("Tmax:" + (max1 - average) + " Cmax:" + (max2 - average) + " 比值=" + maxRatio2);
        SendDisplayMessage("T面积:" + areaLeft[1] + " C面积:" + areaRight[1] + " 比值=" + s1s2Ratio2);
        SendDispAreaMessage("面积 " + area1 + " " + area2 + " 极值 " + max1 + " " + max2);

        //保存数据
//        saveData();
        return areaLeft[0] + "\t" + areaRight[0] + "\t" + areaLeft[1] + "\t" + areaRight[1] + "\t" + max1 + "\t" + (max1 - average) + "\t" + average;
    }

    //给定点，算左右1mm的面积
    //首先计算左点外10个点和右点外10个点的平均值
    //再计算左右1mm内值减去平均值后的面积
    int nPointsForAverageLeft = 10, nPointsForAverageRight = 10;

    private int CalcArea(int[] data, int iMax, int step, int averageGlobal, int[] area2) {
        int nData = 0, sum = 0;
        for (int iData = iMax - left * step - nPointsForAverageLeft; iData < iMax - left * step; iData++) {
            if (iData <= 0)
                continue;
            sum += data[iData];
            nData++;
        }
        for (int iData = iMax + right * step; iData < iMax + right * step + nPointsForAverageRight * step; iData++) {
            if (iData >= data.length)
                break;
            sum += data[iData];
            nData++;
        }
        if (nData == 0)
            return -1;
        int average = sum / nData;
        int area = 0, areaSubGlobalAvg = 0;
        for (int iData = iMax - left * step; iData < iMax + right * step; iData++) {
            if (iData < 0 || iData >= data.length) {
                Log.d("area", "Data index error:" + iData);
                continue;
            }
            area += (data[iData] - average) / step;
            areaSubGlobalAvg += (data[iData] - averageGlobal) / step;
        }
        Log.d("", "area: " + area + " average: " + average);
        Log.d("", "areaSubGlobalAvg: " + areaSubGlobalAvg + " averageGlobal: " + averageGlobal);
        if (area2 != null) {
            area2[0] = area;
            area2[1] = areaSubGlobalAvg;
        }
        return area;
    }

    private void ResetBtnClicked() {
        mBtn365.setBackgroundColor(Color.BLUE);
        mBtn470.setBackgroundColor(Color.BLUE);
        mBtn525_1.setBackgroundColor(Color.BLUE);
        mBtn525_2.setBackgroundColor(Color.BLUE);
    }

    private void SetBtnClicked(Button btn) {
        ResetBtnClicked();
        btn.setBackgroundColor(Color.CYAN);
    }

    private void OpenLED365() {
        SetBtnClicked(mBtn365);
        color = 0x15;
        mbLED470Clicked = false;
        LEDOn();
    }

    private void OpenLED470() {
        SetBtnClicked(mBtn470);
//        color=0x2a;
        mbLED470Clicked = true;
        SetColor470();
        LEDOn();
    }

    private void OpenLED525_1() {
        SetBtnClicked(mBtn525_1);
        color = 0x40;
        mbLED470Clicked = false;
        LEDOn();
    }

    private void OpenLED525_2() {
        SetBtnClicked(mBtn525_2);
        color = (byte) 0x80;
        mbLED470Clicked = false;
        LEDOn();
    }

    //用户点击了灯，设置下灯的位
    private void SetColor() {
        color = 0x00;
        if (mcbColor1.isChecked())
            color |= 0x01;
        if (mcbColor2.isChecked())
            color |= 0x02;
        if (mcbColor3.isChecked())
            color |= 0x04;
        if (mcbColor4.isChecked())
            color |= 0x08;
        if (mcbColor5.isChecked())
            color |= 0x10;
        if (mcbColor6.isChecked())
            color |= 0x20;
    }

    private boolean LEDOn() {
        mDeviceHID.Skip();
        ledPosition = 0x03;
        int brightness = mSBBrightness.getProgress();
        if (!mDeviceHID.LEDOn(ledPosition, color, brightness)) {
            SendDisplayMessage("开灯失败");
            return false;
        } else {
            SendDisplayMessage("开灯成功");
            return true;
        }
    }

    private boolean LEDOff() {
        mDeviceHID.Skip();
        ResetBtnClicked();
//        if (!mDeviceHID.LEDOff())
        ledPosition = 0x03;
        if (!mDeviceHID.LEDOn(ledPosition, (byte) 0x00, 0)) {
            SendDisplayMessage("关灯失败");
            return false;
        } else {
            SendDisplayMessage("关灯成功");
            return true;
        }
    }

    private void Home() {
        if (!mDeviceHID.GoHome())
            DisplayMessage("回原点失败");
        else
            DisplayMessage("回原点成功");
    }

    private void TrayOut() {
        if (!mDeviceHID.TrayOut())
            DisplayMessage("托架取出失败");
        else
            DisplayMessage("托架取出成功");
    }

    private void TrayIn() {
        if (!mDeviceHID.TrayIn())
            DisplayMessage("托架移动进入失败");
        else
            DisplayMessage("托架移动进入成功");
    }

    private void TrayMoveStart() {
        int dist = Integer.parseInt(mEdtStart.getText().toString());
        if (!mDeviceHID.MoveTray(dist))
            DisplayMessage("托架移动起点失败");
        else
            DisplayMessage("托架移动起点成功");
    }

    private void TrayMoveEnd() {
        int dist = Integer.parseInt(mEdtStop.getText().toString());
        if (dist > 250) {
            dist = 250;
            mEdtStop.setText("250");
        }
        if (!mDeviceHID.MoveTray(dist))
            DisplayMessage("托架移动终点失败");
        else
            DisplayMessage("托架移动终点成功");
    }

    //    private void Read() {
//        int[] data = new int[10];
//        String strADGain = mEdtADGain.getText().toString();
//        if (!mDeviceHID.GetAD(adPosition, (byte) Integer.parseInt(strADGain), data)) {
//            DisplayMessage("读数据失败");
//            return;
//        }
//        DisplayData(data);
//    }
//    private void DisplayData(int[] data) {
//        String csMsg = "";
//        for (int i = 0; i < 10; i++) {
//            csMsg += mstrWaveLength[i] + ":" + data[i] + "\t";
//        }
//        DisplayMessage(csMsg);
//    }
    private void Read() {
        getADPosition();
        String strADGain = mEdtADGain.getText().toString();
        mDeviceHID.StartADReceive(adPosition);
        mDeviceHID.GetADAfterStart();
        mDeviceHID.GetADAfterStart();
        mDeviceHID.GetADAfterStart();
        int data = mDeviceHID.GetADAfterStart();
        mDeviceHID.StopADReceive();
        if (data < 0) {
            DisplayMessage("读数据失败");
            return;
        }
        DisplayMessage("AD:" + data);
    }

    private void getADPosition() {
        if (mrgADPosition.getCheckedRadioButtonId() == R.id.rbADPosition1)
            adPosition = 0x01;
        else
            adPosition = 0x02;
    }

    void getStartStop() {
        mStart = Integer.parseInt(mEdtStart.getText().toString());
        mStop = Integer.parseInt(mEdtStop.getText().toString());
        if (mStop > 250) {
            mStop = 250;
            mEdtStop.setText("250");
        }
        if (!getStep())
            mStep = Integer.parseInt(mEdtStep.getText().toString());
    }

    private void ScanRead() {
        getStartStop();
        getADPosition();

        saveSettings();

        new Test().start();
    }

    private void saveSettings() {
        SettingsClass.setMainRedBrightness(mSBBrightness.getProgress());
        SettingsClass.setMainRedStart(mStart);
        SettingsClass.setMainRedStop(mStop);
        SettingsClass.saveSettings();
    }

    int iStrip = 0;
    String resultFileName;

    boolean getStep() {
        int[] frequencyAndGain = new int[2];
        if (!mDeviceHID.GetADCFrequencyAndGain((byte) 0x01, frequencyAndGain))
            return false;
        if (frequencyAndGain[0] < 10 || frequencyAndGain[0] > 19200)
            return false;
        mStep = (int) (frequencyAndGain[0] / 50.0 + 0.5);
        if (mStep <= 0)
            mStep = 1;
        return true;
    }

    void SendDisplayMessage(String str) {
        Message message = new Message();
        message.what = 1;
        message.obj = str;
        mHandler.sendMessage(message);
    }

    void SendDispAreaMessage(String str) {
        Message message = new Message();
        message.what = 5;
        message.obj = str;
        mHandler.sendMessage(message);
    }

    void SendDispAverageMessage(String str) {
        Message message = new Message();
        message.what = 6;
        message.obj = str;
        mHandler.sendMessage(message);
    }

    void SendDispData(int[] data) {
        Message message = new Message();
        message.what = 2;
        message.obj = data;
        mHandler.sendMessage(message);
    }

    void SendDispData(int data) {
        Message message = new Message();
        message.what = 4;
        message.obj = data;
        mHandler.sendMessage(message);
    }

    void DispCurve() {
        Message message = new Message();
        message.what = 3;
        mHandler.sendMessage(message);
    }

    public File getSaveFile() {
        File file = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            file = Environment.getExternalStorageDirectory();
        } else {
            file = getFilesDir();
        }

        if (file != null) {
            file = new File(file, "stresscube");
            if (!file.exists()) {
                file.mkdir();
            }
            file = new File(file, "scantestpd");
            if (!file.exists()) {
                file.mkdir();
            }
        }

        return file;
    }

    public String getDateString() {
        Calendar c = Calendar.getInstance();
        c.setTime(new Date(System.currentTimeMillis()));
        String formatString = "yyyyMMddHHmmss";
        SimpleDateFormat sdf = new SimpleDateFormat(formatString, Locale.ENGLISH);
        return sdf.format(c.getTime());
    }

    private String getDataFilename() {
        return getSaveFile() + "/" + getDateString() + ".txt";
    }

    class Test extends Thread {
        @Override
        public void run() { //改成发移动命令、连续获取AD、检测停止命令
            SendDisplayMessage("开始测试");

            if (!scanReadAD(true, mStart, mStop, mStep, mListResult))
                return;

            if (mListResult.size() > 10) {
                int[] data = new int[mListResult.size()];
                for (int i = 0; i < mListResult.size(); i++)
                    data[i] = mListResult.get(i);
                GetArea(data, mStep);
                if (SaveData(data))
                    SendDisplayMessage("保存数据成功");
                else
                    SendDisplayMessage("保存失败！");
            }
        }

        //把测试数据保存下来
        private boolean SaveData(int[] data) {
            byte position = 0x01, indexLED = 0x02;
            try {
                String resultFileName = getDataFilename();
                FileOutputStream out = new FileOutputStream(resultFileName);
                out.write(("" + mStart + " -> " + mStop + "\r\n").getBytes());
                out.write(("面积1: " + mArea1 + " 面积2:" + mArea2 + "\r\n").getBytes());
                for (int i = 0; i < data.length; i++) {
                    out.write(("" + data[i] + "\r\n").getBytes());
                }
                out.flush();
                out.close();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    }

    private int GetAverage(int[] data, int iMaxLeft, int iMaxRight, int step) {
//        int iStart=0;
//        if(mStart<40)
//            iStart=40-mStart;
//        int iStop=datas.length;
//        if(mStop>80&&mStart<80)
//            iStop=80-mStart;
//        int[] newDatas=new int[iStop-iStart];
//        for(int i=iStart;i<iStop;i++)
//            newDatas[i-iStart]=datas[i];
        int[] newDatas = new int[data.length];
        for (int i = 0; i < data.length; i++)
            newDatas[i] = data[i];
        for (int i = 0; i < 5; i++)
            newDatas[i] = -1;
        for (int i = iMaxLeft - left * step; i < iMaxLeft + left * step; i++) {
            if (i <= 0)
                continue;
            newDatas[i] = -1;
        }
        for (int i = iMaxRight - right * step; i < iMaxRight + right * step; i++) {
            if (i >= data.length)
                break;
            newDatas[i] = -1;
        }
        int average = 0;
        while (true) {
            double sum = 0;
            int num = 0;
            int max = -1, imax = -1;
            int min = 0, imin = -1;
            for (int i = 0; i < newDatas.length; i++)
                if (newDatas[i] > 0) {
                    sum += newDatas[i];
                    num++;
                    if (imax < 0 || max < newDatas[i]) {
                        max = newDatas[i];
                        imax = i;
                    }
                    if (imin < 0 || min > newDatas[i]) {
                        min = newDatas[i];
                        imin = i;
                    }
                }
            average = (int) (sum / num + 0.5);
            if (num <= 10)
                break;
            if (max < average * 1.05 && min > average / 1.05)
                break;
            if (max >= average * 1.05)
                newDatas[imax] = -1;
            if (min <= average / 1.05)
                newDatas[imin] = -1;
        }
        SendDispAverageMessage("平均值 ：" + average);
        return average;
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1:
                    DisplayMessage((String) msg.obj);
                    break;
                case 2:
//                    DisplayData((int[]) msg.obj);
                    break;
                case 3:
                    DrawLineChart();
                    break;
                case 4:
                    DisplayMessage("AD: " + (int) msg.obj);
                    break;
                case 5:
                    DisplayAreaMessage((String) msg.obj);
                    break;
                case 6:
                    DisplayAverageMessage((String) msg.obj);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private void ClickF8ClearNIR(int i) {
        bF8ClearNIR[i - 1] = !bF8ClearNIR[i - 1];
        DrawLineChart();
    }

    private void DrawLineChart() {
        if (mListResult == null || mListResult.size() <= 0) {
            Toast.makeText(this, "没有数据", Toast.LENGTH_LONG).show();
            return;
        }

        List<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
//        for (int fx = 0; fx < 10; fx++) {
//            if (!bF8ClearNIR[fx]) continue;
        List<Entry> entries = new ArrayList<Entry>();
//            for (int i = 0; i < mListResult.get(fx).size(); i++) {
//                entries.add(new Entry(mStart + i * mStep, mListResult.get(fx).get(i)));
//            }
        for (int i = 0; i < mListResult.size(); i++)
            entries.add(new Entry(mStart + i * 1.0f / mStep, mListResult.get(i)));
//            LineDataSet dataSet = new LineDataSet(entries, mstrWaveLength[fx]);
//        int color = GetColor(fx);
        LineDataSet dataSet = new LineDataSet(entries, "ad");
        int color = GetColor(0);
        dataSet.setColor(color);
        dataSet.setValueTextColor(color);
        dataSet.setCircleColor(color);
        dataSet.setCircleHoleColor(color);
        dataSets.add(dataSet);
//        }
        LineData data = new LineData(dataSets);
        mLineChart.setData(data);
        mLineChart.invalidate(); // refresh
    }

    int[] colors = {Color.RED, Color.GREEN, Color.BLUE, Color.GRAY, Color.DKGRAY, Color.LTGRAY, Color.CYAN, Color.BLACK, Color.MAGENTA, Color.WHITE};

    private int GetColor(int i) {
        return colors[i % 10];
    }

    /**
     * 保存数据
     */
    private void saveData() {
        DataBean dataBean = new DataBean();
        dataBean.time = System.currentTimeMillis();
        //编号
        dataBean.number = etNumber.getText().toString().trim();
        dataBean.create_time = SCTimeUtils.getFormatData03(dataBean.time);

        dataBean.project = etProject.getText().toString().trim();

        //两个面积
        dataBean.area1 = mArea1;
        dataBean.area2 = mArea2;

        dataBean.ad = ((EditText) findViewById(R.id.edtADGain)).getText().toString().trim();
        dataBean.start = ((EditText) findViewById(R.id.edtStart)).getText().toString().trim();
        dataBean.stop = ((EditText) findViewById(R.id.edtStop)).getText().toString().trim();
        //步长
        dataBean.step = ((EditText) findViewById(R.id.edtStep)).getText().toString().trim();
        //波长
        dataBean.waveLength = waveLength;
        //亮度
        dataBean.brightness = ((TextView) findViewById(R.id.tvBrightness)).getText().toString().trim();

        if (((RadioButton) findViewById(R.id.rbPeakOrValley_Peak)).isChecked()) {
            //选择的是胶体金
            dataBean.jtj_or_yg = "1";
        } else {
            dataBean.jtj_or_yg = "2";
        }

        dataBean.save();
    }

    boolean scanReadAD(boolean bOpenLed, int start, int stop, int step, List<Integer> listResult) {
        mDeviceHID.StopADReceive();
        mDeviceHID.Skip();
        mDeviceHID.GoHome();

        if (bOpenLed && !LEDOn()) {
            return false;
        }
        listResult.clear();
        mDeviceHID.Skip();
        if (!mDeviceHID.MoveTray(start)) {
            if (!mDeviceHID.MoveTray(start)) {
                SendDisplayMessage("移动到起点位置 " + start + " 失败");
                mDeviceHID.StopADReceive();
                mDeviceHID.LEDOn(ledPosition, (byte) 0x00, 0);
                mDeviceHID.MoveTray(0);
                return false;
            }
        }
        mDeviceHID.StartADReceive(adPosition);
        mDeviceHID.StartMoveTray(stop);
        mDeviceHID.GetADAfterStart();
        mDeviceHID.GetADAfterStart();
        mDeviceHID.GetADAfterStart();
        int nData = 0;
        while (true) { //连续读
            int data = mDeviceHID.GetADAfterStart();
            if (data <= 0) {
                break;
            }
            listResult.add(data);
            if(nData>0&&nData%10==0)
                DispCurve();
            nData++;
            if (nData > (stop - start) * step + 100) {
                SendDisplayMessage("没有接收到停止命令，强制停止");
                break;
            }
        }
        mDeviceHID.StopADReceive();
        if (bOpenLed)
            LEDOff();
        mDeviceHID.MoveTray(0);
        return true;
    }
}